package cn.com.mjsoft.framework.persistence.core.support.transform;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;

import org.apache.log4j.Logger;

import cn.com.mjsoft.framework.persistence.core.PersistenceEngine;
import cn.com.mjsoft.framework.persistence.core.JdbcInstrument;
import cn.com.mjsoft.framework.persistence.core.RowTransform;
import cn.com.mjsoft.framework.persistence.core.support.EntitySqlBridge;
import cn.com.mjsoft.framework.util.ObjectUtility;

/**
 * 将一行数据转换为指定类型对象
 * 
 * @author mjsoft
 * 
 */
public class EntityForGetTransform implements RowTransform
{
    private static final Logger log = Logger.getLogger( EntityForGetTransform.class );

    private Class<?> targetEntityClazz;

    public EntityForGetTransform( Class<?> entityClazz )
    {
        this.targetEntityClazz = entityClazz;
    }

    public Class<?> getTargetEntityClazz()
    {
        return targetEntityClazz;
    }

    public Object convertRow( ResultSet rs, int rowNum ) throws SQLException
    {
        EntitySqlBridge bridge = PersistenceEngine.getEntitySql( targetEntityClazz );

        Object pojo = null;
        try
        {
            pojo = ObjectUtility.buildObject( targetEntityClazz );
        }
        catch ( Exception e )
        {
            log.error( e );
            throw new SQLException( "目标pojo对象创建失败" );
        }

        /**
         * 为什么用index是安全的，因为这些相关sql中的字段顺序是按照注册<br>
         * 时候的顺序，永远会对应到正确的字段。
         */
        int index = 1;
        Iterator<String> keyIterator = bridge.getFieldNameIterator();
        while ( keyIterator.hasNext() )
        {
            Field fe = bridge.getPojoSqlField( keyIterator.next() );
            ObjectUtility.setPrivateFieldValue( fe, pojo,
                JdbcInstrument.getResultSetColumnValue( rs, index++, fe.getType() ) );
        }

        return pojo;
    }
}
